<!-- 智慧停车场登录 -->
<template>
    <div id="box">
        <el-card>
            <template #header>
                <h3>智慧停车场登录</h3>
            </template>
            <el-form ref="ruleFormRef" :model="admin" :rules="rules">
                <el-form-item label="账号" props="account">
                    <el-input v-model="admin.account" placeholder="默认账号admin" />
                </el-form-item>
                <el-form-item label="密码" props="password">
                    <el-input v-model="admin.password" placeholder="默认密码123456" type="password" show-password @keyup.enter="adminLogin"/>
                </el-form-item>
                <el-button type="danger" @click="adminLogin">登录</el-button>
            </el-form>
        </el-card>
    </div>
</template>
<script setup lang="ts">
import { ref,reactive } from 'vue';
import type { FormInstance,FormRules } from 'element-plus';
import { adminLoginAPI } from "@/api/admin";
import { ElMessage } from 'element-plus';
import { useRouter } from "vue-router";
// 路由
const router = useRouter();
// 表单规则
const ruleFormRef = ref<InstanceType<typeof FormInstance>>();

const admin = reactive({
    account: "",
    password: ""
});
// 自定义密码校验
const validatePass = (rule: any, value: any, callback: any) => {
    if (!/^\w{3,}$/.test(value)) {
        callback(new Error("密码最少3位"));
    } else {
        callback();
    }
}
// 用户名密码校验规则
const rules = reactive<InstanceType<typeof FormRules>>({
    account: [{ required: true, message: "账号不能为空", trigger: 'blur' }],
    password: [{ required: true, validator: validatePass, trigger: 'blur' }],
})
function adminLogin() {
    //   保证表单验证通过
    ruleFormRef.value.validate((valid: Boolean) => {
        if (valid) {
            // 表单验证通过,发送axios
            adminLoginAPI({
                // 请求时传递的参数
                account: admin.account,
                password: admin.password
            }).then(resp => {
                if (resp.data.code == 20000) {
                    // 提示登录成功
                    ElMessage({
                        message: '登录成功!',
                        type: 'success',
                    })
                    // 存储数据
                    localStorage.setItem("id",resp.data.data[0].id);
                    localStorage.setItem("adminname", resp.data.data[0].account);
                    localStorage.setItem("role", resp.data.data[0].role);
                    // 跳转
                    router.push("/home")
                }else if(resp.data.code == 50000){
                    ElMessage.error(resp.data.msg)
                }
            })
        }
    })
}
</script>
<style lang="less" scoped>
#box {
    width: 100%;
    height: 100%;
    background: linear-gradient(to right, rgb(255, 219, 213), rgb(255, 122, 46));
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .el-card {
        width: 400px;

        .el-button {
            width: 100%;
        }
    }
}
</style>